//
//  PictureSelectorCollectionViewController.swift
//  Weibo
//
//  Created by 张远文 on 16/5/10.
//  Copyright © 2016年 张远文. All rights reserved.
//

import UIKit

private let reuseIdentifier = "PictureSelectorCell"
private let column: CGFloat = 4
private let pictureCellMargin: CGFloat = 10
private let maxImageCount = 3

class PictureSelectorCollectionViewController: UICollectionViewController {

    //添加图片数组属性
    lazy var imageList = [UIImage]()
    
    init() {
        let layout = UICollectionViewFlowLayout()
        //设置layout
        let w = (screenW - (column + 1) * pictureCellMargin) / column
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumLineSpacing = pictureCellMargin
        layout.minimumInteritemSpacing = pictureCellMargin
        //设置section间距
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView?.backgroundColor = UIColor(colorLiteralRed: 0.5, green: 0.5, blue: 0.2, alpha: 0.7)
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageList.count + ((imageList.count == maxImageCount) ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
    
        // Configure the cell
        cell.selectorCellDelegate = self
        cell.backgroundColor = UIColor.clearColor()
        
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
    
        return cell
    }
}

//实现自定义cell代理方法
extension PictureSelectorCollectionViewController: PictureSelectorCellDelegate {
    
    func userWillAddPicture(cell: PictureSelectorCell) {
        
        if cell.image != nil {
            print("已经添加图片")
            return
        }
        print("添加图片")
        let picker = UIImagePickerController()
        //指定代理
        picker.delegate = self
        
        //弹出图片选择器
        //picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePicture(cell: PictureSelectorCell) {
        //获取cell的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex((indexPath?.item)!)
        
        //刷新视图
        UIView.animateWithDuration(0.5, animations: { 
            
            cell.alpha = 0
            }) { (_) in
                cell.alpha = 1
                self.collectionView?.reloadData()
        }
    }
}

//遵守图片选择器的协议
extension PictureSelectorCollectionViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //添加图片
        imageList.append(image)
        //刷新集合视图
        collectionView?.reloadData()
        //一旦实现协议方法 dismiss 就交给程序员
        dismissViewControllerAnimated(true, completion: nil)
    }
}

@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {
    //定义协议方法
    //添加图片的协议方法
    optional func userWillAddPicture(cell: PictureSelectorCell)
    
    //删除图片的协议方法
    optional func userWillDeletePicture(cell: PictureSelectorCell)
}

class PictureSelectorCell: UICollectionViewCell {
    //定义代理
    weak var selectorCellDelegate: PictureSelectorCellDelegate?
    
    //按钮监听方法
    @objc private func addBtnDidClick() {
        selectorCellDelegate?.userWillAddPicture?(self)
    }
    
    @objc private func deleteBtnDidClick() {
        selectorCellDelegate?.userWillDeletePicture?(self)
    }
    
    //定义图片数据类型
    var image: UIImage? {
        didSet {
            deleteBtn.hidden = (image == nil)
            if image != nil {
                addBtn.setBackgroundImage(image, forState: .Normal)
            } else {
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    }
    
    
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    private func setupUI() {
        //添加子视图
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        //添加事件
        addBtn.addTarget(self, action: #selector(addBtnDidClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(deleteBtnDidClick), forControlEvents: .TouchUpInside)
    }
    
    //懒加载控件
    private lazy var addBtn: UIButton = UIButton(title: nil, backImage: "compose_pic_add", color: nil)
    private lazy var deleteBtn: UIButton = UIButton(title: nil, backImage: "compose_photo_close", color: nil)
}
